package com.atguigu.order.controller;


import com.atguigu.commonutils.JwtUtils;
import com.atguigu.commonutils.R;
import com.atguigu.order.entity.Order;
import com.atguigu.order.entity.vo.OrderQuery;
import com.atguigu.order.entity.vo.OrderVo;
import com.atguigu.order.service.OrderService;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.List;

/**
 * <p>
 * 订单 前端控制器
 * </p>
 *
 * @author lgy
 * @since 2022-04-26
 */
@RestController
//@CrossOrigin
@RequestMapping("/edu_order/order")
public class OrderController {

    @Autowired
    private OrderService orderService;

    //1 生成订单的方法
    @PostMapping("createOrder/{courseId}")
    public R saveOrder(@PathVariable String courseId, HttpServletRequest request) {
        //创建订单，返回订单号
        String orderNo =
                orderService.createOrders(courseId,JwtUtils.getMemberIdByJwtToken(request));
        return R.ok().data("orderId",orderNo);
    }

    //2 根据订单id查询订单信息
    @GetMapping("getOrderInfo/{orderId}")
    public R getOrderInfo(@PathVariable String orderId) {
        QueryWrapper<Order> wrapper = new QueryWrapper<>();
        wrapper.eq("order_no",orderId);
        Order order = orderService.getOne(wrapper);
        return R.ok().data("item",order);
    }

    //根据【用户id、课程id】查询订单表中的状态
    @GetMapping("/isBuyCourse/{memberId}/{courseId}")
    public Boolean isBuyCourse(@PathVariable String memberId,@PathVariable String courseId)	  {
        QueryWrapper<Order> wrapper = new QueryWrapper<>();
        wrapper.eq("course_id",courseId);
        wrapper.eq("member_id",memberId);
        wrapper.eq("status",1);//支付状态 【1】代表已支付
        int result = orderService.count(wrapper);

        if (result>0){//已支付
            return true;
        }else {
            return false;
        }
    }

    //订单条件查询
    @ApiOperation(value="订单条件查询")
    @PostMapping("/getOrders/{page}/{limit}")
    public R getOrdersPage(@ApiParam(name = "page", value = "当前页码", required = true)@PathVariable Long page, @ApiParam(name = "limit", value = "每页记录数", required = true)@PathVariable Long limit, @RequestBody(required = false) OrderQuery orderQuery){
        orderQuery.setPage(page-1);
        orderQuery.setLimit(limit);
        List<OrderVo> records = orderService.getOrdersPage(orderQuery);

        //获取总记录数
        int total = orderService.count(null);
        return R.ok().data("total",total).data("rows",records);
    }



}


